package com.chukun.concurrency.concurrencyCollections;

import com.chukun.concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
import java.util.concurrent.*;

/**
 * ConcurrentHashMap使用链表+数组实现，可以实现高并发的性能
 */
@Slf4j
@ThreadSafe
public class ConcurrentHashMapOperator {


    //并发线程总数
    private static final int totalThreadCount=1000;

    //允许同时访问的总数
    private static final int allowThreadCount = 200;

    private static Map<Integer,Integer> map=new ConcurrentHashMap<>();

    public static void main(String[] args) {

        CountDownLatch countDownLatch = new CountDownLatch(totalThreadCount);
        Semaphore semaphore = new Semaphore(allowThreadCount);
        ExecutorService executorService = Executors.newCachedThreadPool();

        for(int i=0;i<totalThreadCount;i++){
            final int count=i;
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    add(count);
                    semaphore.release();
                }catch (Exception e){
                    log.error("error count add ",e);
                }
                countDownLatch.countDown();
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        System.out.println("size: "+ map.size());
    }

    private static void add(int i){
        map.put(i,i);
    }
}
